<?php

namespace app\api\controller;

use app\BaseController;
use think\facade\View;
use think\facade\Config;
use think\facade\Request;
// use think\facade\Session;
use app\common\model\SystemAdmin;
use app\common\model\Store;
use app\common\model\User;
use app\common\model\Material;
use app\common\model\MaterialBanner;
use app\common\model\MaterialType;
use app\common\model\Product;
use app\common\model\ProductType;
use app\common\model\ProductBanner;
use app\common\model\FileLog;
use app\common\controller\Handle;
use GatewayWorker\Lib\Gateway;
use think\Exception;
use think\facade\Db;

class ApiMaterial extends ApiBase
{
    public function initialize()
    {
        parent::initialize();
        $this->Material = new Material;
        $this->Store = new Store;
        $this->MaterialType = new MaterialType;
        $this->MaterialBanner = new MaterialBanner;
        $this->FileLog = new FileLog;
        $this->Product = new Product;
        $this->ProductType = new ProductType;
        $this->ProductBanner = new ProductBanner;
    }

    // 查询分类
    public function getType()
    {
       
        $typeList = $this->MaterialType->order('sort asc')->order('id',"asc")->field("id,name,sort,parent_id")->select()->toArray();

        if(!empty($typeList)){
            $data = list_to_tree($typeList);
        }else{
            $data = [];
        }
        return json(['status' => 1, 'data' => $data]);

    }


    // 添加素材
    public function  addMaterial()
    {
        // 判断店铺是否正常
        $is_store = $this->storeIsNormal($this->uid);

        if($is_store['code'] == 1){
            return json(['status' => 0, 'msg' =>$is_store['msg']]);
        }
 
        $store_id = $is_store['store_id'];

        $data = request()->post();

        if(empty($data['name'])){
            return json(['status' => 0, 'msg' =>"请上传主题"]);
        }

        if(empty($data['type_id'])){
            return json(['status' => 0, 'msg' =>"请选择类型"]);
        }

        if(empty($data['logo'])){
            return json(['status' => 0, 'msg' =>"请选择封面"]);
        }


        if(empty($data['content'])){
            return json(['status' => 0, 'msg' =>"请上传内容"]);
        }

       

        if(empty($data['video_or_banner'])){
            return json(['status' => 0, 'msg' =>"请选择上传展示素材轮播图还是小视频"]);
        }

        $add = [
            "name"=>$data['name'],
            "type_id"=>$data['type_id'],
            "logo"=>$data['logo'],
            "content"=>$data['content'],
            "video_or_banner"=>$data['video_or_banner'],
            "store_id"=>$store_id,
            "user_id"=>$this->uid,
            "created_at"=>date("Y-m-d H:i:s"),
            "update_at"=>date("Y-m-d H:i:s"),
            'audit'=>1,
        ];

       

        if($data['video_or_banner'] == 1){
            if(empty($data['video_url'])){
                return json(['status' => 0, 'msg' =>"请上传视频路径"]);
            }
            $add['video_url'] = $data['video_url'];
        }else{
            if(empty($data['banner_list'])){
                return json(['status' => 0, 'msg' =>"请上传轮播图片路径"]);
            }
        }
        
        if(!empty($data['type_child_id'])){
            $add['type_child_id'] = $data['type_child_id'];
        }


        if(!empty($data['sort'])){
            $add['sort'] = $data['sort'];
        }

        if(!empty($data['status'])){
            $add['status'] = $data['status'];
        }

        // 开启事务
        Db::startTrans();
        try {

            $res = $this->Material->create($add);
            $material_id = $res->id;
            $addBanner = [];
            if($data['video_or_banner'] == 2){
                foreach($data['banner_list'] as $k=>$v){
                    $addBanner[] = [
                        "material_id"=>$material_id,
                        "file_url"=>$v,
                        "sort"=>$k+1,
                        "created_at"=>date("Y-m-d H:i:s"),
                        "update_at"=>date("Y-m-d H:i:s"),
                    ];
                }

                $resBanner = $this->MaterialBanner->insertAll($addBanner);
            }

            // 提交事务
            Db::commit();
            return json(['status' => 1, 'msg' => '操作成功']);
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['status' => 0, 'msg' =>$e->getMessage()]);
        }
    }


    // 素材列表
    public function listMaterial()
    {

        // 存储空间对应的域名
        $domain = config('sysconfig.qiniu_domain');


        // 判断店铺是否正常
        $is_store = $this->storeIsNormal($this->uid);

        if($is_store['code'] == 1){
            return json(['status' => 0, 'msg' =>$is_store['msg']]);
        }

        $store_id = $is_store['store_id'];

        $where['deleted_at'] = null;

        if(!empty($data['type_id'])){
            $where['type_id'] = $data['type_id'];
        }

        if(!empty($data['type_child_id'])){
            $where['type_child_id'] = $data['type_child_id'];
        }

        if(!empty($data['store_id'])){
            $where['store_id'] = $store_id;
        }else{
            $where['status'] = 1;
        }

        
        if(empty($data['limit'])){
            $data['limit'] = 10;
        }

        if(empty($data['page'])){
            $data['page'] = 1;
        }

        $list = $this->Material->getPagelist($where,"id,name,sort,logo,type_id,status",'sort asc');

        foreach($list as $key=>$val){
            // $val->logo = $domain."/".$val['logo'];
            $val->type_name = $this->MaterialType->where(['id'=>$val['type_id']])->value("name");
            
            
        }

        $count = $this->Material->countRows($where);

        $pages = ceil($count/$data['limit']);

        return json(['status'=> 1,'data'=>$list,'pages'=>$pages,"count"=>$count]);
    }

   
    // 素材详情
    public function getMaterial()
    {
        // 存储空间对应的域名
        $domain = config('sysconfig.qiniu_domain');

        // 判断店铺是否正常
        $is_store = $this->storeIsNormal($this->uid);

        if($is_store['code'] == 1){
            return json(['status' => 0, 'msg' =>$is_store['msg']]);
        }
 
        $store_id = $is_store['store_id'];

        $data = request()->post();

        if(empty($data['id'])){
            return json(['status' => 0, 'msg' =>"请上传素材ID"]);
        }

        $list = $this->Material->getOne(['id' =>$data['id'],'deleted_at'=>null]);

        if(empty($list)){
            return json(['status' => 0, 'msg' =>"素材不存在"]);
        }


        $list['content'] = str_replace("api_project",$domain."/api_project",$list['content']);

        if(empty($list)){
            return json(['status' => 0, 'msg' =>"请素材不存在"]);
        }

        // $list['logo'] = $domain."/".$list['logo'];

        $list['type_name'] = $this->MaterialType->where(['id'=>$list['type_id']])->value("name");

        if(!empty($list['type_child_id'])){
            $list['type_child_name'] = $this->MaterialType->where(['id'=>$list['type_child_id']])->value("name");
        }else{
            $list['type_child_name'] = "";
        }

        if($list['video_or_banner'] == 2){
            $list['banner_list'] = $this->MaterialBanner->where(["material_id"=>$data['id']])->field("id,file_url")->select();

            // if(!empty($list['banner_list'])){
            //     foreach($list['banner_list'] as $key=>$val){
            //         $val->file_url = $domain."/".$val['file_url'];
            //     }
            // }
        }

        
        return json(['status'=> 1,'data'=>$list]);


    }

    // 修改素材
    public function  updateMaterial()
    {
        // 判断店铺是否正常
        $is_store = $this->storeIsNormal($this->uid);

        if($is_store['code'] == 1){
            return json(['status' => 0, 'msg' =>$is_store['msg']]);
        }

        $store_id = $is_store['store_id'];

        $data = request()->post();


        if(empty($data['id'])){
            return json(['status' => 0, 'msg' =>"请上传素材ID"]);
        }

        $list = $this->Material->getOne(['id' =>$data['id'],'store_id'=>$store_id,'deleted_at'=>null]);

        if(empty($list)){
            return json(['status' => 0, 'msg' =>"请素材不存在"]);
        }
        if(empty($data['name'])){
            return json(['status' => 0, 'msg' =>"请上传素材主题"]);
        }

        if(empty($data['type_id'])){
            return json(['status' => 0, 'msg' =>"请选择素材类型"]);
        }

        if(empty($data['logo'])){
            return json(['status' => 0, 'msg' =>"请选择素材封面"]);
        }

        if(empty($data['content'])){
            return json(['status' => 0, 'msg' =>"请上传内容"]);
        }
        if(empty($data['video_or_banner'])){
            return json(['status' => 0, 'msg' =>"请选择上传展示素材轮播图还是小视频"]);
        }

        $save = [
            "name"=>$data['name'],
            "type_id"=>$data['type_id'],
            "logo"=>$data['logo'],
            "content"=>$data['content'],
            "video_or_banner"=>$data['video_or_banner'],
            "store_id"=>$store_id,
            "user_id"=>$this->uid,
            "update_at"=>date("Y-m-d H:i:s"),
        ];

        

        $save['content'] = str_replace($domain."/api_project","api_project",$list['content']);

        if($data['video_or_banner'] == 1){
            if(empty($data['video_url'])){
                return json(['status' => 0, 'msg' =>"请上传视频路径"]);
            }
            $save['video_url'] = $data['video_url'];
        }else{
            if(empty($data['banner_list'])){
                return json(['status' => 0, 'msg' =>"请上传轮播图片路径"]);
            }
        }


        if(!empty($data['type_child_id'])){
            $save['type_child_id'] = $data['type_child_id'];
        }else{
            $save['type_child_id'] = null;
        }

        if(!empty($data['sort'])){
            $save['sort'] = $data['sort'];
        }

        if(!empty($data['status'])){
            $save['status'] = $data['status'];
        }

        // 开启事务
        Db::startTrans();
        try {

            $res = $this->Material->where(['id'=>$data['id']])->update($save);
            $resBanner = $this->MaterialBanner->where(["material_id"=>$data['id']])->delete();
            $addBanner = [];
            if($data['video_or_banner'] == 2){
                foreach($data['banner_list'] as $k=>$v){
                    $addBanner[] = [
                        "material_id"=>$data['id'],
                        "file_url"=>$v,
                        "sort"=>$k+1,
                        "created_at"=>date("Y-m-d H:i:s"),
                        "update_at"=>date("Y-m-d H:i:s"),
                        "deleted_at"=>date("Y-m-d H:i:s"),
                    ];
                }

                $resBanner = $this->MaterialBanner->insertAll($addBanner);
            }

            // 提交事务
            Db::commit();
            return json(['status' => 1, 'msg' => '操作成功']);
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['status' => 0, 'msg' =>$e->getMessage()]);
        }
    }

     // 删除素材
     public function  delMaterial()
     {
         // 判断店铺是否正常
         $is_store = $this->storeIsNormal($this->uid);
 
         if($is_store['code'] == 1){
             return json(['status' => 0, 'msg' =>$is_store['msg']]);
         }
 
         $store_id = $is_store['store_id'];
 
         $data = request()->post();
 
 
         if(empty($data['id'])){
             return json(['status' => 0, 'msg' =>"请上传素材ID"]);
         }
 
         $list = $this->Material->getOne(['id' =>$data['id'],'store_id'=>$store_id,'deleted_at'=>null]);
 
         if(empty($list)){
             return json(['status' => 0, 'msg' =>"请素材不存在"]);
         }
 
 
         // 开启事务
         Db::startTrans();
         try {
 
             $res = $this->Material->where(['id'=>$data['id'],'store_id'=>$store_id])->update(["deleted_at"=>date("Y-m-d H:i:s")]);
 
             // 提交事务
             Db::commit();
             return json(['status' => 1, 'msg' => '操作成功']);
         } catch (Exception $e) {
             // 回滚事务
             Db::rollback();
             return json(['status' => 0, 'msg' =>$e->getMessage()]);
         }
     }
    // 一键导入
    public function toLead()
    {
        // 判断店铺是否正常
        $is_store = $this->storeIsNormal($this->uid);

        if($is_store['code'] == 1){
            return json(['status' => 0, 'msg' =>$is_store['msg']]);
        }

        $store_id = $is_store['store_id'];


        $data = request()->post();
 
        if(empty($data['id'])){
            return json(['status' => 0, 'msg' =>"请上传素材ID"]);
        }

        $where[] = ["id","IN",$data['id']];

        $list = $this->Material->getAllOrder($where,"",'sort asc');

        Db::startTrans();
        try {
            foreach($list as $key=>$val){
                $typeName =  $this->MaterialType->where(['id'=>$val['type_id']])->value("name");
                $typeNameChild =  $this->MaterialType->where(['id'=>$val['type_child_id']])->value("name");
    
    
                $typeId = $this->ProductType->where(['name'=>$typeName,"parent_id"=>0])->value("id");
    
                if(empty($typeId)){
                    $addType = [
                        "parent_id"=>0,
                        "name"=>$typeName,
                        "store_id"=>$store_id,
                        "sort"=>99,
                        "created_at"=>99,
                        "update_at"=>99,
                    ];
    
                    $resType = $this->ProductType->create($addType);
                    $typeId = $resType->id;
                }
    
    
                $typeChildId = $this->ProductType->where(['name'=>$typeNameChild,"parent_id"=>$typeId])->value("id");
    
                if(empty($typeChildId)){
                    $addTypeChild = [
                        "parent_id"=>$typeId,
                        "name"=>$typeName,
                        "store_id"=>$store_id,
                        "sort"=>99,
                        "created_at"=>99,
                        "update_at"=>99,
                    ];
    
                    $resTypeChild = $this->ProductType->create($addTypeChild);
                    $typeChildId = $resTypeChild->id;
                }
    
                $addProduct = [
                    "name"=>$val['name'],
                    "type_id"=>$val['type_id'],
                    "type_child_id"=>$val['type_child_id'],
                    "logo"=>$val['logo'],
                    "content"=>$val['content'],
                    "video_or_banner"=>$val['video_or_banner'],
                    "video_url"=>$val['video_url'],
                    "bargain_set"=>2,
                    "status"=>2,
                    "store_id"=>$store_id,
                ];
    
    
                $res = $this->Product->create($addProduct);
    
                $productId = $res->id;
    
                if($val['video_or_banner'] == 2){
                    $listBanner  = $this->MaterialBanner->where(['id'=>$val['id']])->select();
                    $addBanner = [];
                    foreach($listBanner as $k=>$v){
                        $addBanner[] = [
                            "product_id"=>$productId,
                            "file_url"=>$v['file_url'],
                            "created_at"=>date("Y-m-d H:i:s"),
                            "update_at"=>date("Y-m-d H:i:s"),
                        ];
                    }
    
                    $res = $this->ProductBanner->insertAll($addBanner);
                }
            }
            // 提交事务
            Db::commit();
            return json(['status' => 1, 'msg' => '操作成功']);
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['status' => 0, 'msg' =>$e->getMessage()]);
        }

      

 
    }

    // 上传素材图片或者视频
    public function addFile()
    {
        $file = request()->file('file');

        if (!$file) {
            return ['status' => 0, 'msg' => '上传失败，图片不存在'];
        }

        // 获取文件原始扩展名
        $extension = $file->extension();

        $hand = new Handle();

        $dirname = "api_project";

        $savename = $hand->qiniuImg("file", $dirname);

        $add['file_name'] = $savename['fileName'];
        $add['upload_type'] = 2;
        $add['file_path'] = $savename['url'];
        $add['file_type'] = $extension;
        $add['ip'] = Request::ip();
        $add['add_time'] = time();
        $add['user_id'] = $this->uid;
        
        $res = $this->FileLog->create($add);
        $fileLogId = $res->id;
        $savename['file_id'] = $fileLogId;

        return  json($savename);
    }


    // 删除文件
    public function delFile()
    {
        $data = request()->post();

        // 存储空间对应的域名
        $domain = config('sysconfig.qiniu_domain');

        if(empty($data['url'])){
            return json(['status' => 0, 'msg' =>"请上传要删除文件的url"]);
        }


        // 要去掉的子串
        // $substring =  $domain.'/';

        // 使用 str_replace() 函数去掉子串
        // $data['url'] = str_replace($substring, '', $data['url']);

        $hand = new Handle();

        $res = $hand->delQIniuImg($data['url']);

        return  json($res);
    }
   
}
